<script setup>
import { ref } from 'vue';
import axios from 'axios';
import { checkLogin} from '../../../js/login.js';
import Navbar from '@/components/Navbar.vue';
import BackgroundImage from '@/components/BackgroundImage.vue';
const backgroundImage = '/src/assets/images/测试.jpg';
//先检测是否登录
checkLogin();

const fileName = ref('');
const selectedFile = ref(null);

const onFileChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    fileName.value = file.name;
    selectedFile.value = file;
    console.log(`文件名: ${file.name}`);
  }
};

const confirmUpload = async () => {
  if (!selectedFile.value) {
    console.error('没有选择文件');
    return;
  }

  const formData = new FormData();
  formData.append('file', selectedFile.value);

  try {
    const response = await axios.post('http://localhost:8000/crud/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    console.log('文件上传成功:', response.data);
    fileName.value = '';
    selectedFile.value = null;
  } catch (error) {
    console.error('文件上传失败:', error);
  }
};

</script>


<template>
    <BackgroundImage :backgroundImage="backgroundImage">
      <Navbar />
      <!-- 添加文件上传按钮 -->
      <div>
        <input type="file" id="fileInput" accept=".jpg,.png,.jpeg" @change="onFileChange" />
        <button @click="confirmUpload">确认上传</button>
      </div>
    </BackgroundImage>
</template>


<style scoped>

</style>